//
//  HLocationView.m
//  HTanzhi
//
//  Created by 陈贵 on 15/12/5.
//  Copyright © 2015年 hzj. All rights reserved.
//

#import "HLocationView.h"
#import "MyAnnotation.h"
///查询位置时显示的个数
#define THEPOSITIONCOUNT  1
//起始时的地图跨度
#define THESTARLATITUDE  0.016559426907427621
#define THESTARLONGITUDE  0.013732909468274102

@interface HLocationView ()<MKMapViewDelegate>
///地图
@property (nonatomic ,strong) MKMapView *myMap;
///定位
@property (nonatomic ,strong) CLLocationManager *mar;
///收缩文本框
@property (nonatomic ,strong) UITextField *myText;
@end

@implementation HLocationView

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUI];
    
    self.mar = [[CLLocationManager alloc]init];
    if ([self.mar respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.mar requestWhenInUseAuthorization];
    }
    //更新位置最小距离
    self.mar.distanceFilter = 10;
    //精确度 (减少为卫星之间的计算, 以此实现省电)
    self.mar.desiredAccuracy = kCLLocationAccuracyKilometer;
    
    //显示样式（卫星、混合等）
    self.myMap.mapType = MKMapTypeHybrid;
    //定位模式
    self.myMap.userTrackingMode = MKUserTrackingModeFollow;
    
    //ios9新特性(显示交通、指南针、比例)
    self.myMap.showsTraffic = YES;
    self.myMap.showsCompass = YES;
    self.myMap.showsScale = YES;
    self.myMap.delegate = self;
    
}
///设置UI
- (void) setUI{
    CGFloat w = [UIScreen mainScreen].bounds.size.width;
    CGFloat h = [UIScreen mainScreen].bounds.size.height;
    
    self.myMap = [[MKMapView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.myMap];
    //搜索文本
    self.myText = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, w * 0.3, w * 0.1)];
    self.myText.text = @"天津市";
    [self.view addSubview:self.myText];
    //搜索
    UIButton *searchB = [self addBthWithImage:nil andTitle:@"搜索" andAction:@selector(starPositionServe)];
    searchB.frame = CGRectMake(CGRectGetMaxX(self.myText.frame), 0, w * 0.2, w * 0.1);
    //路线
    UIButton *navigateLineB = [self addBthWithImage:nil andTitle:@"开始导航" andAction:@selector(theNavigateLine)];
    navigateLineB.backgroundColor = [UIColor brownColor];
    navigateLineB.frame = CGRectMake(CGRectGetMaxX(searchB.frame), 0, w * 0.2, w * 0.1);
    //放大
    UIButton *biggerB = [self addBthWithImage:nil andTitle:@"大" andAction:@selector(zoomBigger)];
    biggerB.frame = CGRectMake(0, h * 0.2, w * 0.1, w * 0.1);
    //缩小
    UIButton *smallerB = [self addBthWithImage:nil andTitle:@"小" andAction:@selector(zoomSmaller)];
    smallerB.frame = CGRectMake(CGRectGetMaxX(biggerB.frame), biggerB.frame.origin.y, w * 0.1, w * 0.1);

    //返回当前位置
    UIButton *returnB = [self addBthWithImage:nil andTitle:@"返回" andAction:@selector(clickReturnBth)];
    returnB.frame = CGRectMake(0, h * 0.5, w * 0.1,w * 0.1);
    
}
///搜索
- (void) starPositionServe{
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder geocodeAddressString:self.myText.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count == 0 || error) {
            return ;
        }
        /*
        CLPlacemark *pm = placemarks.firstObject;
        //获取经纬度
        CLLocationCoordinate2D coordinate = pm.location.coordinate;
        */
        
        //遍历
        [placemarks enumerateObjectsUsingBlock:^(CLPlacemark * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == THEPOSITIONCOUNT - 1 || obj == nil) {
                *stop = YES;
            }
            //自定义大头针显示内容
            MyAnnotation *annotation = [[MyAnnotation alloc]init];
            annotation.coordinate = obj.location.coordinate;
            if (obj.locality) {
                annotation.title = obj.locality;
            }else{
                annotation.title = obj.subAdministrativeArea;
            }
            annotation.subtitle = obj.name;
            [self.myMap addAnnotation:annotation];
        }];
        
//        CLPlacemark *pm = placemarks.firstObject;
//        MyAnnotation *annotation = [[MyAnnotation alloc]init];
//        annotation.coordinate = pm.location.coordinate;
//        annotation.title = @"haode";
//        [self.myMap addAnnotation:annotation];
    }];
}
///放大
- (void) zoomBigger{
    
    //当前中心
    CLLocationCoordinate2D center = self.myMap.region.center;
    //跨度
    CLLocationDegrees latitude = self.myMap.region.span.latitudeDelta * 2;
    CLLocationDegrees longitude = self.myMap.region.span.longitudeDelta * 2;
    //限制跨度
    if (latitude > 140 || longitude > 140) {
        return;
    }
    MKCoordinateSpan span = MKCoordinateSpanMake(latitude , longitude);
    
    [self.myMap setRegion:MKCoordinateRegionMake(center, span) animated:YES];
//    0.016559426907427621 0.013732909468274102
}
///缩小
- (void) zoomSmaller{
    //当前中心
    CLLocationCoordinate2D center = self.myMap.region.center;
    //当前跨度
    CLLocationDegrees latitude = self.myMap.region.span.latitudeDelta;
    CLLocationDegrees longitude = self.myMap.region.span.longitudeDelta;
    //改变后的跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(latitude * 0.5, longitude * 0.5);
    [self.myMap setRegion:MKCoordinateRegionMake(center, span) animated:YES];
}
///返回当前位置
- (void) clickReturnBth{
    //用户位置重点
    CLLocationCoordinate2D center = self.myMap.userLocation.location.coordinate;
    //地图跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(THESTARLATITUDE, THESTARLONGITUDE);
    
    [self.myMap setRegion:MKCoordinateRegionMake(center, span) animated:YES];
}

#pragma mark - MapView 代理方法
///定位更新时
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count == 0 || error) {
            return ;
        }
        CLPlacemark *pm = placemarks.firstObject;
        if (pm.locality) {
            userLocation.title = pm.locality;
        }else{
            userLocation.title = pm.administrativeArea;
        }
        userLocation.subtitle = pm.name;
    }];
    
}
///在此法中更改大头针样式
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    static NSString *ID = @"annotationView";
    
#pragma mark - 需自定义图片代替大头针时：MKAnnotationView；不需时：MKPinAnnotationView
    /*
    MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if ( annotationView == nil) {
        annotationView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:ID];
        annotationView.image = [UIImage imageNamed:@"sina-denglu-1"];
    }
    */
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if ( annotationView == nil) {
        annotationView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:ID];
    }
//    //设置属性视图
    annotationView.canShowCallout = YES;
    annotationView.leftCalloutAccessoryView = [self addBthWithImage:nil andTitle:@"试" andAction:@selector(clickTheLeftView) andRect:CGRectMake(0, 0, 20, 20)];
    annotationView.rightCalloutAccessoryView = [[UISwitch alloc]init];
    //ios9新
    annotationView.detailCalloutAccessoryView = [[UISwitch alloc]init];
    return annotationView;
}
- (void) clickTheLeftView{
    UIViewController *vc = [[UIViewController alloc]init];
    vc.view.backgroundColor = [UIColor brownColor];
    [self.navigationController pushViewController:vc animated:YES];
    
}
///在此法中添加动画
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views{
    for (MKAnnotationView *annotationView in views) {
        //判断是否为定位点
        if ([annotationView.annotation isKindOfClass:[MKUserLocation class]]) {
            return;
        }
        //记录先前位置
        CGRect starF = annotationView.frame;
        annotationView.center = CGPointMake(starF.origin.x + starF.size.width, 0);
        [UIView animateWithDuration:0.5 animations:^{
            annotationView.frame = starF;
        }];
    }
}

#pragma mark - 导航
- (void) theNavigateLine{
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    [geocoder geocodeAddressString:self.myText.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        CLPlacemark *placemark = placemarks.firstObject;
        
        MKMapItem *sourceItem = [MKMapItem mapItemForCurrentLocation];
        
        MKMapItem *destinationItem = [[MKMapItem alloc]initWithPlacemark:(MKPlacemark *)placemark];
        
        //导航请求
        MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
        //导航起点
        request.source = sourceItem;
        //导航终点
        request.destination = destinationItem;
        
        //导航方向对象
        MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
        
        [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
            
            NSLog(@"%@",response);
            if (response.routes.count == 0 || error) {
                return ;
            }
            
            for (MKRoute *route in response.routes) {
                MKPolyline *polyline = route.polyline;
                [self.myMap addOverlay:polyline];
            }
        }];
    }];
     
}
#pragma mark - 设置地图渲染物
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    
    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc]initWithOverlay:overlay];
    //属性
    renderer.strokeColor = [UIColor redColor];
    renderer.lineWidth = 1;
    return renderer;
}

///生成按钮
- (UIButton *) addBthWithImage:(NSString *)iconName andTitle:(NSString *)title andAction:(SEL)action andRect:(CGRect)rect{
    UIButton *bth = [UIButton buttonWithType:UIButtonTypeCustom];
    bth.frame = rect;
    if (iconName) {
        UIImage *imageB = [UIImage imageNamed:iconName];
        if (!imageB) {
            NSLog(@"请确认图片名");
        }
        NSLog(@"yongle");
        [bth setImage:imageB forState:UIControlStateNormal];
    }
    //背景色
    [bth setBackgroundColor:[UIColor grayColor]];
    //字体大小
    [bth.titleLabel setFont:[UIFont systemFontOfSize:13]];
    //字体颜色
    [bth setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //事件
    [bth addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [bth setTitle:title forState:UIControlStateNormal];
    [self.view addSubview:bth];
    return bth;
}
- (UIButton *) addBthWithImage:(NSString *)iconName andTitle:(NSString *)title andAction:(SEL)action{
    
    UIButton *bth = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (iconName) {
        UIImage *imageB = [UIImage imageNamed:iconName];
        if (!imageB) {
            NSLog(@"请确认图片名");
        }
        NSLog(@"yongle");
        [bth setImage:imageB forState:UIControlStateNormal];
    }
    //背景色
    [bth setBackgroundColor:[UIColor grayColor]];
    //字体大小
    [bth.titleLabel setFont:[UIFont systemFontOfSize:13]];
    //字体颜色
    [bth setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //事件
    [bth addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [bth setTitle:title forState:UIControlStateNormal];
    
    [self.view addSubview:bth];
    return bth;
}
- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.myText resignFirstResponder];
}
@end
